<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  SwitchButton,
  Calendar,
  View,
  Box,
  DataAnalysis,
  DocumentCopy,
  Operation,
  Finished,
  Umbrella,
  Grid,
  DocumentAdd,
} from '@element-plus/icons-vue'


const router = useRouter()
const currentTime = ref('')
let timer: number | null = null

// 监听路由变化，确保标题始终正确
router.afterEach(() => {
  setPageTitle()
})

// 用户信息
const userInfo = ref<any>(null)

// 计算属性：获取用户信息
const userName = computed(() => {
  return userInfo.value?.name || '未登录'
})

const userRole = computed(() => {
  return userInfo.value?.role || '游客'
})

const userOrganization = computed(() => {
  return userInfo.value?.organizationStructure || ''
})

// 获取用户信息
const getUserInfo = () => {
  try {
    const storedUserInfo = localStorage.getItem('userInfo')
    if (storedUserInfo) {
      const parsedUserInfo = JSON.parse(storedUserInfo)
      console.log('解析到的用户信息:', parsedUserInfo)

      // 处理字段名大小写问题
      userInfo.value = {
        id: parsedUserInfo.Id || parsedUserInfo.id || 0,
        account: parsedUserInfo.Account || parsedUserInfo.account || '',
        name: parsedUserInfo.Name || parsedUserInfo.name || '',
        role: parsedUserInfo.Role || parsedUserInfo.role || '',
        organizationStructure: parsedUserInfo.OrganizationStructure || parsedUserInfo.organizationStructure || ''
      }

      console.log('处理后的用户信息:', userInfo.value)
    } else {
      userInfo.value = null
    }
  } catch (error) {
    console.error('解析用户信息失败:', error)
    userInfo.value = null
  }
}

// 处理登录
const handleLogin = () => {
  router.push('/login')
}

// 设置页面标题
const setPageTitle = () => {
  document.title = 'iMES-您的新一代工厂管家【商业版】'
}

// 处理登出
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 清除本地存储
    localStorage.removeItem('userInfo')
    localStorage.removeItem('token')
    userInfo.value = null

    ElMessage.success('已退出登录')
    router.push('/login')
  } catch (error) {
    // 用户取消操作
  }
}

const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}

const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}

const updateTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')

  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const weekday = weekdays[now.getDay()]

  currentTime.value = `${year}.${month}.${day} ${hours}:${minutes}:${seconds} ${weekday}`
}


onMounted(() => {
  // 设置页面标题
  setPageTitle()

  getUserInfo()
  updateTime()
  timer = setInterval(updateTime, 1000)

  // 确保标题始终正确
  const titleTimer = setInterval(setPageTitle, 1000)

  // 监听页面可见性变化
  const handleVisibilityChange = () => {
    if (!document.hidden) {
      setPageTitle()
    }
  }

  document.addEventListener('visibilitychange', handleVisibilityChange)

  // 清理标题定时器和事件监听器
  onUnmounted(() => {
    if (titleTimer) {
      clearInterval(titleTimer)
    }
    document.removeEventListener('visibilitychange', handleVisibilityChange)
  })
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>
<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="logo-section">
            <h1 class="imes-logo">IMES</h1>
          </div>

          <!-- 用户信息区域 -->
          <div class="user-info-section">
            <div v-if="userInfo" class="user-info">
              <div class="user-avatar">
                <span class="avatar-text">IMES</span>
              </div>
              <div class="user-details">
                <div class="user-info-row">
                  <span class="user-name">{{ userName }}</span>
                  <span class="user-role">{{ userRole }}</span>
                </div>
                <div class="current-time">{{ currentTime }}</div>
              </div>
              <el-button type="text" size="small" @click="handleLogout" class="logout-btn">
                <el-icon>
                  <SwitchButton />
                </el-icon>
              </el-button>
            </div>

            <!-- 未登录状态 -->
            <div v-else class="login-section">
              <el-button type="primary" size="large" @click="handleLogin" class="login-btn">
                立即登录
              </el-button>
            </div>
          </div>
        </div>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-menu default-active="5" class="el-menu-vertical-demo" @open="handleOpen" router @close="handleClose">
            <el-sub-menu index="1">
              <template #title>
                <el-icon>
                  <Setting />
                </el-icon>
                <span>系统设置</span>
              </template>
              <el-menu-item index="/Useroperation">用户管理</el-menu-item>
              <el-menu-item index="/Role_Management">角色管理</el-menu-item>
              <el-menu-item index="/Permission_management">权限管理</el-menu-item>
              <el-menu-item index="/SystemLog">系统日志</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="2">
              <template #title>
                <el-icon>
                  <Calendar />
                </el-icon>
                <span>排班管理</span>
              </template>
              <el-menu-item index="/Team_management">班组管理</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="3">
              <template #title>
                <el-icon>
                  <View />
                </el-icon>
                <span>看板管理</span>
              </template>
              <el-menu-item index="/Kanban_Management">看板管理</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="4">
              <template #title>
                <el-icon>
                  <Box />
                </el-icon>
                <span>库存管理</span>
              </template>
              <el-menu-item index="WarehouseReceipt">入库单</el-menu-item>
              <el-menu-item index="OutboundOrder">出库单</el-menu-item>
              <el-menu-item index="/Inventory_balance">库存余额</el-menu-item>
              <el-menu-item index="/InventoryTransaction">库存收发明细</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="5">
              <template #title>
                <el-icon>
                  <DataAnalysis />
                </el-icon>
                <span>基础数据</span>
              </template>
              <el-menu-item index="/DefectItem">不良品项目</el-menu-item>
              <el-menu-item index="/WorkProcess">工序管理</el-menu-item>
              <el-menu-item index="/ProcessRoute">工艺路线</el-menu-item>
              <el-menu-item index="/Product">产品管理</el-menu-item>
              <el-menu-item index="/BillOfMaterial">物料清单</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="6">
              <template #title>
                <el-icon>
                  <DocumentCopy />
                </el-icon>
                <span>报表管理</span>
              </template>
              <el-menu-item index="/report-management">
                <el-icon>
                  <Grid />
                </el-icon>
                <span>报表页面</span>
              </el-menu-item>


            </el-sub-menu>

            <el-sub-menu index="7">
              <template #title>
                <el-icon>
                  <Operation />
                </el-icon>
                <span>生产管理</span>
              </template>
              <el-menu-item index="/SalesOrder">销售订单</el-menu-item>
              <el-menu-item index="/ProductionPlan">生产计划</el-menu-item>
              <el-menu-item index="/AssemblyWorkOrder">装配工单</el-menu-item>
              <el-menu-item index="/WorkOrder">工单</el-menu-item>
              <el-menu-item index="/Task">任务</el-menu-item>
              <el-menu-item index="/WorkReporting">报工</el-menu-item>
              <el-menu-item index="/Completion_Order">完工单</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="8">
              <template #title>
                <el-icon>
                  <Finished />
                </el-icon>
                <span>生产计划管理</span>
              </template>
              <el-menu-item index="/NewProductionPlan">生产计划列表</el-menu-item>
            </el-sub-menu>


            <el-sub-menu index="9">
              <template #title>
                <el-icon>
                  <Umbrella />
                </el-icon>
                <span>天气预报</span>
              </template>
              <el-menu-item index="/Weather">天气预报</el-menu-item>
            </el-sub-menu>
          </el-menu>
          
 
        </el-aside>


        <el-main>
          <RouterView />
        </el-main>
      </el-container>
    </el-container>
  </div>




</template>

<style scoped>
.common-layout,
.common-layout>.el-container {
  height: 100vh;
}

/* 头部高度为60px，下面的主容器占满剩余高度 */
.common-layout>.el-container>.el-container {
  height: calc(100vh - 60px);
}

.el-header {
  background: #409eff;
  color: white;
  padding: 0 20px;
  height: 60px;
  line-height: 60px;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
}

.logo-section {
  display: flex;
  align-items: center;
}

.imes-logo {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
  color: white;
}

.user-info-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border: 2px solid white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  flex-shrink: 0;
  margin-top: 2px;
}

.avatar-text {
  font-size: 12px;
  font-weight: bold;
  color: white;
}

.user-details {
  display: flex;
  flex-direction: column;
  line-height: 1.3;
  text-align: left;
  min-width: 120px;
  gap: 4px;
}

.user-info-row {
  display: flex;
  align-items: center;
  gap: 8px;
  line-height: 1.2;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: white;
}

.user-role {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.9);
}

.current-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.9);
  min-width: 180px;
  text-align: left;
  flex-shrink: 0;
}

.logout-btn {
  color: white;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.3s ease;
  flex-shrink: 0;
  background: transparent;
  border: none;
}

.logout-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  transform: scale(1.1);
}

.logout-btn .el-icon {
  font-size: 16px;
}

.login-section {
  display: flex;
  align-items: center;
}

.login-btn {
  background: #67c23a;
  border-color: #67c23a;
  font-weight: 600;
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.login-btn:hover {
  background: #85ce61;
  border-color: #85ce61;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
}

.el-aside {
  background: #f5f5f5;
  border-right: 1px solid #e6e6e6;
  height: 100%;
  overflow: auto;
  /* 侧边栏可滚动 */
}

.el-main {
  background: #fff;
  padding: 0;
  overflow: hidden;
}

/* 菜单样式优化 */
.el-menu {
  border-right: none;
  height: 100%;
  overflow: auto;
  /* 菜单可滚动，避免展开后看不到底部 */
}

/* 隐藏滚动条但保留滚动功能（兼容主流浏览器） */
:deep(.el-aside),
:deep(.el-menu) {
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}

:deep(.el-aside::-webkit-scrollbar),
:deep(.el-menu::-webkit-scrollbar) {
  width: 0;
  /* Chrome/Safari/Edge */
  height: 0;
}

.el-menu-item {
  height: 50px;
  line-height: 50px;
}

.el-sub-menu__title {
  height: 50px;
  line-height: 50px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .user-info {
    gap: 10px;
  }

  .current-time {
    min-width: 140px;
    font-size: 11px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 10px 0;
  }

  .user-info-section {
    margin: 10px 0;
    flex-direction: column;
    gap: 10px;
  }

  .user-info {
    flex-direction: column;
    text-align: center;
  }

  .login-section {
    margin: 10px 0;
  }

  .el-aside {
    width: 100% !important;
  }
}
</style>
